<?php
	namespace app\service\admin;
	use core\BaseService;
	use app\model\Role;
	use core\Util;
	use app\model\RoleUser;
	use core\ParamFilter;
	use app\model\User;
	class RoleService extends BaseService{
		function model(){
			return Role::$tableName;
		}
		
		function saveRole($params,$info){
			if($params['id']){
				$params = Role::filter($params);
				$this->update($params);
				$info->success =true;
				$info->msg = '操作成功，数据已更新！';
			}else{
				$params = Role::filter($params);
				$time = Util::time();
				$params["create_time"] = $time;
				$this->insert($params);
				$info->success =true;
				$info->msg = '操作成功，数据已保存！';
			}
		}
		
		function queryAuthUserByFilter($filter){
			$mTable = $this->table(RoleUser::$tableName);
			$mTableName = RoleUser::$tableName;
			$user = User::$tableName;
			$role = Role::$tableName;
			$mTable->join($user,$mTableName.'.user_id','=',$user.'.id')
					->join($role,$mTableName.'.role_id','=',$role.'.id')
					->select($mTableName.'.id as id',$role.'.name as role_name',$user.'.login_name');
			$this->queryByFilter($filter,$mTable);
		}
		
		function delRoleUserByFilter($filter){
			$mTable = RoleUser::$tableName;
			return $this->deleteByFilter($filter,$this->table($mTable));
		}
		
		
		/**
		 *获取当前用户的权限
		 */
		function getRolesByUserId($userId){
			$mTable = RoleUser::$tableName;
			return $this->table()
				->join($mTable,
					$this->model().'.id', '=', 
					$mTable.'.role_id')
				->where($mTable.'.user_id',$userId)
				->select($this->model().'.*')
				->get();
		}
		
		/**
		 *更新用户的权限
		 */
		function updateUserRole($userIds,$roleIds,$info){
			$mTable = $this->table(RoleUser::$tableName);
			//删除用户原有的权限
			$filter = new ParamFilter();
			$filter->addFilter("Q_user_id_in",$userIds);
			$this->deleteByFilter($filter,$mTable);

			//添加新的权限
			$mTable = $this->table(RoleUser::$tableName);
			if($roleIds){
				$roleArr = explode(',',$roleIds);
				$userArr = explode(',',$userIds);
				$datas = array();
				$index = 0 ;
				for($i=0;$i<count($roleArr);$i++){
					for($j=0;$j<count($userArr);$j++){
						$datas[$index++] = array(
							"user_id"=>$userArr[$j],
							"role_id"=>$roleArr[$i]
						);
					}
				}
				$mTable->insert($datas);
			}
			$info->success =true;
			$info->msg = '操作成功，用户角色已更新！';
		}
		
		function deleteById($ids,$info){
			$idArr = explode(',',$ids);
			//删除角色
			$count = $this->table()->whereIn('id',$idArr)->delete();
			//删除角色的用户关系
			$this->table(RoleUser::$tableName)->whereIn('role_id',$idArr)->delete();
			$info->success = true;
			$info->msg = "操作成功，已删除".$count."条数据！";
		}
		
	}